import { Classify } from '../models';
import { updateClassifyFromRedis } from '../bin/init';

export default function (router) {
  /**
   * 后台获取分类
   */
  router.get('/api/admin/classify', async ctx => {
    const { keyword } = ctx.request.query;
    let condition = {};
    if (keyword) {
      condition.$or = [{ name: new RegExp(keyword, 'i') }, { desc: new RegExp(keyword, 'i') }];
    }
    const { page, limit } = ctx.parsePageAndLimit(ctx.request.query);
    const total = await Classify.countDocuments(condition);
    const classifys = await Classify.find(condition)
      .skip((page - 1) * limit)
      .limit(limit)
      .sort({ priority: 1, create_time: 1 });
    await ctx.json(true, 'success', { list: classifys, total });
  });

  /**
   * 后台新增分类
   */
  router.post('/api/admin/classify', async ctx => {
    const { name, des } = ctx.request.body;
    if (!name) {
      await ctx.json(false, '参数错误');
      return false;
    }
    const maxPriority = await Classify.countDocuments();
    const newClassify = await Classify.create({
      name,
      des,
      priority: maxPriority + 1,
      create_time: Date.now()
    });

    if (newClassify) {
      await updateClassifyFromRedis();
      await ctx.json(true, 'success');
    } else {
      await ctx.json(false, '新增分类失败');
    }
  });

  /**
   * 后台修改分类
   */
  router.put('/api/admin/classify/:id', async ctx => {
    const id = ctx.params.id;
    const { name, des } = ctx.request.body;
    if (!id) {
      await ctx.json(false, '参数错误');
      return false;
    }
    const thisClassify = await Classify.findById(id, '_id');
    if (!thisClassify) {
      await ctx.json(false, '找不到该分类');
      return false;
    }
    const updateResult = await Classify.updateOne(
      { _id: id },
      {
        $set: {
          name,
          des
        }
      }
    );
    if (updateResult.ok) {
      await updateClassifyFromRedis();
      await ctx.json(true, 'success');
    } else {
      await ctx.json(false, '更新分类失败');
    }
  });

  /**
   * 后台分类排序
   */
  router.post('/api/admin/classify/exchange', async ctx => {
    const { from: fromIndex, to: toIndex, id } = ctx.request.body;
    if (!fromIndex || !toIndex) await ctx.json(false, '参数错误');
    if (fromIndex === toIndex) await ctx.json(false, '交换顺序不能相同');

    let updateCur, updateOther;
    if (fromIndex > toIndex) {
      updateOther = await Classify.updateMany({ priority: { $lt: fromIndex, $gte: toIndex } }, { $inc: { priority: 1 } });
      updateCur = await Classify.updateOne({ _id: id }, { $set: { priority: toIndex } });
    } else {
      updateOther = await Classify.updateMany({ priority: { $gt: fromIndex, $lte: toIndex } }, { $inc: { priority: -1 } });
      updateCur = await Classify.updateOne({ _id: id }, { $set: { priority: toIndex } });
    }

    if (updateCur.ok && updateOther.ok) {
      await updateClassifyFromRedis();
      await ctx.json(true, 'success');
    } else {
      await ctx.json(false, '交换失败');
    }
  });

  /**
   * 后台给主题
   */
  router.delete('/api/admin/classify/:id', async ctx => {
    const id = ctx.params.id;
    if (!id) {
      await ctx.json(false, '参数错误');
      return false;
    }
    const thisSetting = await Classify.findById(id, '_id');
    if (!thisSetting) {
      await ctx.json(false, '找不到该分类');
      return false;
    }
    const deleteResult = await Classify.deleteOne({ _id: id });
    if (deleteResult.ok) {
      await updateClassifyFromRedis();
      await ctx.json(true, '删除分类成功');
    } else {
      await ctx.json(false, '删除分类失败');
    }
  });
}
